package com.yzh.booksystem.controller;

import com.yzh.booksystem.dao.DeleteBookDao;
import com.yzh.booksystem.entity.Book;
import com.yzh.booksystem.service.DeleteBookService;
import com.yzh.booksystem.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "DeleteServlet", urlPatterns = "/DeleteServlet")
public class DeleteServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        int id = Integer.parseInt(request.getParameter("id"));
        Book book = new Book();
        book.setId(id);

        DeleteBookService deleteBookService = new DeleteBookService();
        UserService userService = new UserService();
        try {
            if (deleteBookService.isdeleteBook(book)) {
                HttpSession session = request.getSession();
                List<Book> listBooks = userService.total_books_show();
                session.setAttribute("listBooks", listBooks);
                response.setHeader("refresh","3;url=/booksystem/index.jsp");
            } else {
//                response.sendRedirect("/booksystem/index.jsp?error2");//要加上第几个错误，
                request.setAttribute("msg", "删除失败");
                request.getRequestDispatcher("/index.jsp").forward(request,response);
                // 要不然登录进去就是yes，直接提示删除错误
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
